package com.javasm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javasm.common.R;
import com.javasm.dto.DishDto;
import com.javasm.entity.Category;
import com.javasm.entity.Dish;
import com.javasm.service.CategoryService;
import com.javasm.service.DishFlavorService;
import com.javasm.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author：易鑫
 * @Version：1.0
 * @Date：2022/4/21-19:54
 * @Since:jdk1.8
 * @Description:
 */
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //清理所有菜品的缓存数据（下面还有一种方法，两种方法都可以）
        Set key = redisTemplate.keys("dish*");
        redisTemplate.delete(key);
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPageInfo = new Page<>();

        //构造条件查询构造器对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        lambdaQueryWrapper.eq(Dish::getIsDeleted,0);
        //执行查询
        dishService.page(pageInfo,lambdaQueryWrapper);

        //对象拷贝(records不能拷贝进去，因为泛型的属性不同，需要单独拷贝处理)
        BeanUtils.copyProperties(pageInfo,dishDtoPageInfo,"records");
        //拿到List<Dish> records
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = null;
        list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            //对象拷贝(item表示Dish对象)
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null){
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPageInfo.setRecords(list);

        return R.success(dishDtoPageInfo);
    }

    /**
     * 根据菜品id查询菜品信息和对应的口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    /**
     * 修改菜品
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //清理当前类别菜品的缓存数据（局部清理）
        String key = "dish" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);

        dishService.updateWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 根据条件查询菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        List<Dish> list = null;

        //动态的构造key
        String key = "dish" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取缓存数据
         list = (List<Dish>) redisTemplate.opsForValue().get(key);

        //如果存在，直接返回，无需查询数据库
        if (list != null){
            return R.success(list);
        }

        //如果不存在需要查询数据库，将查询到的数据缓存到数据库
        //构造查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //只查询起售的菜品(状态为1)
        lambdaQueryWrapper.eq(Dish::getStatus,1);
        //排序条件
        lambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //未删除的
        lambdaQueryWrapper.eq(Dish::getIsDeleted,0);
        list = dishService.list(lambdaQueryWrapper);
        //将查询到的数据缓存到数据库
        redisTemplate.opsForValue().set(key,list,60,TimeUnit.MINUTES);
        return R.success(list);
    }
}
